package com.ehotting.mqbd.zw.netty.netty;


import com.ehotting.eaf.core.utils.ByteUtils;
import com.ehotting.mqbd.zw.api.constants.ActionConstants;
import com.ehotting.mqbd.zw.api.domain.netty.ShakeHandReq;
import com.ehotting.mqbd.zw.api.domain.netty.ZwCommPacket;
import com.ehotting.mqbd.zw.api.domain.netty.ZwCommPacketHead;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class ZwEncoder extends MessageToByteEncoder<ZwCommPacket> {

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, ZwCommPacket obj, ByteBuf out) {
        ZwCommPacketHead head = obj.getHead();
        short cmd = head.getCmd();
        log.info("zw encoder send msg, cmd is {}",ActionConstants.getByCommandVal(cmd));
        if (cmd == ActionConstants.shakeHand.getZwCommandVal()) {
            // 如果是心跳字符串，则直接发送常量值
            out.writeBytes(ShakeHandReq.content);
        }else {
//            log.info("other command, bytes is {}", JSON.toJSONString(obj));

            obj.convertToHexStr();
            String data = obj.toString();

//            log.info("send data is {}",data);

            out.writeBytes(ByteUtils.hexToByteArray(data));
        }
    }
}
